package com.zhentao.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhentao.common.Result;
import com.zhentao.dto.QueryConditionDto;
import com.zhentao.dto.SummaryQueryResultDto;
import com.zhentao.pojo.DataCollection;
import com.zhentao.service.DataQueryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据查询控制器
 * 根据业务流程需求提供REST API接口
 */
@RestController
@RequestMapping("/api/data-query")
@CrossOrigin(origins = "*")
public class DataQueryController {
    
    @Autowired
    private DataQueryService dataQueryService;
    
    /**
     * 汇总查询
     * 根据业务流程：基于外部数据审计库，根据查询条件、分组维度、输出字段展示对应的汇总数据
     * 支持按照维度进行下钻，最多选择三个分组维度
     */
    @PostMapping("/summary")
    public Result<List<SummaryQueryResultDto>> summaryQuery(@RequestBody QueryConditionDto queryCondition) {
        try {
            List<SummaryQueryResultDto> result = dataQueryService.summaryQuery(queryCondition);
            return Result.success("汇总查询成功", result);
        } catch (Exception e) {
            return Result.error("汇总查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 汇总查询下钻
     * 支持逐级下钻溯源展示到最细粒度的原始数据
     */
    @PostMapping("/summary/drill-down")
    public Result<List<SummaryQueryResultDto>> summaryQueryDrillDown(
            @RequestBody QueryConditionDto queryCondition,
            @RequestParam List<String> drillDownPath) {
        try {
            List<SummaryQueryResultDto> result = dataQueryService.summaryQueryDrillDown(queryCondition, drillDownPath);
            return Result.success("下钻查询成功", result);
        } catch (Exception e) {
            return Result.error("下钻查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 数据查询
     * 根据业务流程：基于外部数据审计库，根据选择的查询条件及输出字段展示对应的数据
     * 支持逐级下钻溯源展示到最细粒度的原始数据
     */
    @PostMapping("/data")
    public Result<IPage<DataCollection>> dataQuery(@RequestBody QueryConditionDto queryCondition) {
        try {
            IPage<DataCollection> result = dataQueryService.dataQuery(queryCondition);
            return Result.success("数据查询成功", result);
        } catch (Exception e) {
            return Result.error("数据查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 原始数据查询
     * 根据业务流程：基于外部原始数据表，根据选择的查询条件及输出字段展示对应的原始数据
     */
    @PostMapping("/raw-data")
    public Result<IPage<DataCollection>> rawDataQuery(@RequestBody QueryConditionDto queryCondition) {
        try {
            IPage<DataCollection> result = dataQueryService.rawDataQuery(queryCondition);
            return Result.success("原始数据查询成功", result);
        } catch (Exception e) {
            return Result.error("原始数据查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 导出查询结果
     * 支持汇总数据、数据查询结果、原始数据的导出
     */
    @PostMapping("/export")
    public ResponseEntity<byte[]> exportQueryResult(
            @RequestBody QueryConditionDto queryCondition,
            @RequestParam String exportType) {
        try {
            byte[] excelData = (byte[]) dataQueryService.exportQueryResult(queryCondition, exportType);
            
            String filename = "export_" + exportType.toLowerCase() + ".xlsx";
            
            return ResponseEntity.ok()
                    .header("Content-Disposition", "attachment; filename=\"" + filename + "\"")
                    .header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                    .body(excelData);
        } catch (Exception e) {
            throw new RuntimeException("导出失败：" + e.getMessage(), e);
        }
    }
    
    /**
     * 获取可用的分组维度
     * 根据业务流程：支持用户手动定义为Level 1, Level 2, Level 3
     */
    @GetMapping("/group-dimensions")
    public Result<List<String>> getAvailableGroupDimensions(@RequestParam String queryType) {
        try {
            List<String> dimensions = dataQueryService.getAvailableGroupDimensions(queryType);
            return Result.success("获取分组维度成功", dimensions);
        } catch (Exception e) {
            return Result.error("获取分组维度失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取可用的输出字段
     * 根据业务流程：汇总查询显示处理表中的数值型字段 + 报关单数量 + 记录数量
     */
    @GetMapping("/output-fields")
    public Result<List<String>> getAvailableOutputFields(@RequestParam String queryType) {
        try {
            List<String> fields = dataQueryService.getAvailableOutputFields(queryType);
            return Result.success("获取输出字段成功", fields);
        } catch (Exception e) {
            return Result.error("获取输出字段失败：" + e.getMessage());
        }
    }
    
    /**
     * 验证查询条件
     * 根据业务流程：验证分组维度数量（最多3个）、列值参数设置等
     */
    @PostMapping("/validate")
    public Result<Boolean> validateQueryCondition(@RequestBody QueryConditionDto queryCondition) {
        try {
            boolean isValid = dataQueryService.validateQueryCondition(queryCondition);
            if (isValid) {
                return Result.success("查询条件验证通过", true);
            } else {
                return Result.error("查询条件验证失败");
            }
        } catch (Exception e) {
            return Result.error("验证失败：" + e.getMessage());
        }
    }
} 